package com.woniu.guoguo.dao;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.woniu.guoguo.controller.component.OrderInfo;
import com.woniu.guoguo.model.Order;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Update;

/**
 * <p>
 *  Mapper 接口
 * </p>
 *
 * @author Richie
 * @since 2020-11-02
 */
public interface OrderMapper extends BaseMapper<Order> {

    @Select("select * from `order` where user_id=#{userId} and menu_id=#{menuId} and state=1 limit 0,1")
    Order findOrderByUserIdAndMenuId(@Param("menuId") int menuId,@Param("userId") int userId);

    @Update("update `order` set state=3 where order_id=#{id}")
    void updateStateTo3ById(Integer orderId);

    @Select({"<script>"+
            "select t1.order_id,t1.user_id,t1.description,t1.price,t1.description,t1.state,t1.shop_id,t1.check_code,t1.menu_id,t1.number,\n" +
            "\t(\n" +
            "\t\tSELECT\n" +
            "\t\t\tmenu_img.img_path \n" +
            "\t\tFROM\n" +
            "\t\t\tmenu_img\n" +
            "\t\tWHERE\n" +
            "\t\t\tmenu_img.menu_id = t1.menu_id\n" +
            "\t\tLIMIT 0, 1 \n" +
            "\t) as img_path\n" +
            "FROM `order` as t1" +
            "<where> " +
            "<if test = 'description !=null'> and description like concat('%',#{description},'%')</if>"+
            "<if test = '1==1'> and  t1.user_id = #{userId}</if>"+
            "</where>"+
            "order by order_id desc " +
            "</script>"})
    IPage<OrderInfo> findOrder(Page<OrderInfo> page , @Param("description") String description, @Param("userId") int userId);
    //更新订单表
    @Update("update `order` set state = 2,check_code='无效' where order_id = #{orderId}")
    void changeOrder(Order order);
    //更新用户表
    @Update("update user set balance =balance + #{price} where user_id = #{userId}")
    void changeUser(Order order);
    //更新商家表
    @Update("update restaurant set income =income - #{price} where restaurant_id = #{shopId}")
    void changShop(Order order);

    @Insert("insert into `order`(user_id,description,price,state,shop_id,check_code,menu_id,number,out_trade_no) values(#{userId},#{description},#{price},#{state},#{shopId},#{checkCode},#{menuId},#{number},#{outTradeNo})")
    void addAOrderBuySys(Order order);

    @Select("select * from `order` where out_trade_no=#{otn}")
    Order findOrderByOutTradeNo(String otn);

}
